﻿using System.Runtime.InteropServices;
using System.Threading;

namespace System
{
    public class HiPerfTimer
    {
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(
            out long lpPerformanceCount);

        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(
            out long lpFrequency);

        private long startTime, stopTime,stopTime2;
        private long freq;

        // Constructor
        public HiPerfTimer()
        {
            startTime = 0;
            stopTime  = 0;

            if (QueryPerformanceFrequency(out freq) == false)
            {
                // high-performance counter not supported
                throw new Exception();
            }
			Start();
        }

        // Start the timer
        public void Start()
        {
            // lets do the waiting threads there work
            Thread.Sleep(0);

            QueryPerformanceCounter(out startTime);
			stopTime = startTime;
        }

        // Stop the timer
        public void Stop()
		{
			stopTime2 = stopTime;
			QueryPerformanceCounter(out stopTime);
		}

        // Returns the duration of the timer (in seconds)
        public double TotalDuration
        {
            get
            {
                return (double)(stopTime - startTime) / (double) freq;
            }
        }
		//Returns the duration of last two stops (in seconds)
		public double LastElapsed
		{
			get
			{
				return (double)(stopTime - stopTime2) / (double)freq;
			}
		}
    }
	public class TimerLog
	{
		HiPerfTimer T = new HiPerfTimer();
		public TimerLog()
		{
		}
		public void Start()
		{
			T.Start();
		}
		public void Log(String S)
		{
			T.Stop();
			Console.WriteLine(T.TotalDuration.ToString("0.000").PadLeft(8) + "-" + T.LastElapsed.ToString("0.000").PadLeft(8) + ": " + S);
		}
	}
}